package com.ems.servlet;

import com.ems.dao.AttendanceDAO;
import com.ems.dao.EmployeeDAO;
import com.ems.model.Attendance;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

import com.ems.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/attendance")
public class AttendanceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String action = request.getParameter("action");

            // 单独处理删除操作
            if ("delete".equals(action)) {
                int attendanceId = Integer.parseInt(request.getParameter("attendanceId"));
                new AttendanceDAO().deleteAttendance(attendanceId);
                response.sendRedirect("attendance?action=list");
                return;
            }

            // 处理添加/更新操作
            Attendance attendance = createAttendanceFromRequest(request);
            AttendanceDAO dao = new AttendanceDAO();

            if ("add".equals(action)) {
                dao.addAttendance(attendance);
            } else if ("update".equals(action)) {
                dao.updateAttendance(attendance);
            }

            response.sendRedirect("attendance?action=list");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "操作失败: " + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/admin/attendance.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String role = user.getRole();
        String empId = user.getUserId();
        String action = request.getParameter("action");

        try {
            AttendanceDAO attendanceDAO = new AttendanceDAO();
            List<Attendance> attendances;

            if ("employee".equals(role)) {
                // 员工只能查看自己的考勤记录
                attendances = attendanceDAO.getAttendancesByEmployee(empId);
            } else if ("search".equals(action)) {
                // 从请求参数获取搜索条件
                String searchEmpId = request.getParameter("empId");
                String name = request.getParameter("name");
                String status = request.getParameter("status");
                Date startDate = null;
                Date endDate = null;

                // 处理日期参数
                if (request.getParameter("startDate") != null &&
                        !request.getParameter("startDate").isEmpty()) {
                    startDate = Date.valueOf(request.getParameter("startDate"));
                }

                if (request.getParameter("endDate") != null &&
                        !request.getParameter("endDate").isEmpty()) {
                    endDate = Date.valueOf(request.getParameter("endDate"));
                }

                // 执行搜索
                attendances = attendanceDAO.searchAttendances(
                        searchEmpId,
                        name,
                        status,
                        startDate,
                        endDate
                );
            } else if ("list".equals(action) || action == null) {
                // 默认显示最近30天的考勤记录
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_MONTH, -30);
                Date startDate = new Date(cal.getTimeInMillis());
                Date endDate = new Date(System.currentTimeMillis());

                attendances = attendanceDAO.searchAttendances(
                        null,
                        null,
                        null,
                        startDate,
                        endDate
                );
            } else {
                // 其他情况显示所有记录
                attendances = attendanceDAO.getAllAttendances();
            }

            request.setAttribute("attendances", attendances);
            request.getRequestDispatcher("/WEB-INF/admin/attendance.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取考勤记录失败: " + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/admin/attendance.jsp").forward(request, response);
        }
    }
    private Attendance createAttendanceFromRequest(HttpServletRequest request) throws ParseException {
        Attendance attendance = new Attendance();

        // 确保获取所有参数
        attendance.setEmpId(request.getParameter("empId"));
        attendance.setStatus(request.getParameter("status"));
        attendance.setLeaveReason(request.getParameter("leaveReason"));

        // 修复日期处理 - 使用更健壮的方式
        String recordDateStr = request.getParameter("recordDate");
        if (recordDateStr != null && !recordDateStr.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                attendance.setRecordDate(sdf.parse(recordDateStr));
            } catch (ParseException e) {
                throw new IllegalArgumentException("无效的日期格式: " + recordDateStr);
            }
        }

        // 处理attendanceId - 允许0值（新增记录）
        String attendanceId = request.getParameter("attendanceId");
        if (attendanceId != null && !attendanceId.isEmpty()) {
            try {
                attendance.setAttendanceId(Integer.parseInt(attendanceId));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("无效的考勤ID: " + attendanceId);
            }
        }

        return attendance;
    }
}